/**
 * @desc    图片管理
 * @author  刘贺[of2220]
 * @company qianmi.com
 * @Date    2017/2/7
 */
"use strict";

import {Store,msg} from 'iflux';
import Immutable from 'immutable';
import CateInfoApi from 'webapi/cateInfo-api';
import ImageInfoApi from 'webapi/imageInfo-api';
import {message} from 'antd';


let appStore = module.exports = Store({
    cateTreeData:Immutable.fromJS([]),          //目录树
    expandedKeys:Immutable.fromJS([]),          //展开的目录树
    curRelateImgInfoData:Immutable.fromJS([]),  //当前目录下的数据信息
    selectNodeId:'0',                            //当前选中的ID 默认为0 及 全部
    pageNum:0,                                  //页码
    pageSize:40,                                //每页数量
    totalCount:0,                               //当前目录下总记录数
});

msg.on('create::new::cate',createNewCate)
    .on('get::cateTree::and::img::by::pid',(selectNodeId)=>{
        appStore.cursor().set('selectNodeId',selectNodeId).set('pageNum',0);
        getCateTreeAndImgByPid();
    })
    .on('update::cate::name',updateCateName)        //更新目录名称
    .on('delete::cate',deleteCate)
    .on('delete::image',deleteImage)
    .on('enter::next::cate',enterNextCate)
    .on('change::page::num',(pageNum)=>{
        appStore.cursor().set('pageNum',pageNum);
        getCateTreeAndImgByPid();
    })
    .on('save::image',saveImage)
    .on('update::image::info',updateImageInfo);


//init
getCategoryTree();
getCateTreeAndImgByPid();

async function getCategoryTree() {
    try {
        let data = await CateInfoApi.getCategoryTree();
        data.unshift({name: "全部", id: "0", pid: "-1"});
        //展开所有目录树
        let expandedKeys = data.map((val,index)=>{
            return val.id
        });
        let result = toTree(data,'id','pid','-1');
        appStore.cursor().set('cateTreeData',Immutable.fromJS(result)).set('expandedKeys',Immutable.fromJS(expandedKeys));
    } catch (e) {
        throw e
    }
}

async function createNewCate() {
    let pid = appStore.data().get('selectNodeId');
    let id = pid === "0" ? Date.now().toString() : pid + '-' + Date.now().toString();
    let name = '未命名文件夹';
    try {
        await CateInfoApi.createNewCate({id, name, pid});
        appStore.cursor().set('pageNum', 0);
        await getCategoryTree();
        await getCateTreeAndImgByPid();
    } catch (e) {
        throw e;
    }
}

async function getCateTreeAndImgByPid() {
    let {selectNodeId:id, pageNum, pageSize} = appStore.data().toJS();
    try {
        let result = await CateInfoApi.getCateTreeAndImgByPid({id, pageNum, pageSize});
        let data = result.data,cateList = [],imgList=[];
        data.forEach((item,index)=>{
            item.isCate?cateList.push(item):imgList.push(item);
        });
        appStore.cursor().set('curRelateImgInfoData', Immutable.fromJS(cateList.concat(imgList))).set('totalCount', result.count)
    } catch (e) {
        throw e;
    }
}

async function updateCateName({id,name}) {
    try {
        await CateInfoApi.updateCateName({id, name});
        await getCategoryTree();
        await getCateTreeAndImgByPid();
    } catch (e) {
        throw e;
    }
}

async function deleteCate({id}) {
    try {
        await CateInfoApi.deleteCate({id});
        appStore.cursor().set('pageNum', 0);
        await getCategoryTree();
        await getCateTreeAndImgByPid();
        message.success('删除成功');
    } catch (e) {
        message.error('删除失败');
        throw e;
    }
}

function enterNextCate(selectNodeId) {
    appStore.cursor().set('selectNodeId',selectNodeId).set('pageNum',0);
    getCateTreeAndImgByPid();
}

async function saveImage({pid=appStore.data().get('selectNodeId'), name, src, fileSize, imgSize}) {
    try {
        await ImageInfoApi.saveImage({pid, name, src, fileSize, imgSize});
        appStore.cursor().set('pageNum', 0);
        await getCateTreeAndImgByPid();
        message.success(`图片${name}上传成功`);
    } catch (e) {
        message.error('上传失败！');
        throw e;
    }
}

async function deleteImage({id}) {
    try {
        await ImageInfoApi.deleteImage({id});
        await getCateTreeAndImgByPid();
        message.success('删除成功');
    } catch (e) {
        message.error('删除失败！');
        throw e;
    }
}

async function updateImageInfo({id,imgInfo}) {
    try {
        await ImageInfoApi.updateImageInfo({id,imgInfo});
        await getCateTreeAndImgByPid();
    } catch (e) {
        message.error('修改失败！');
        throw e;
    }
}

function toTree(arrays,idProp,pidProp,startWith){
    let _this = arrays;
    let children = (_this,pid,deep)=>{
        deep = deep ||0;
        let childList = [];
        _this.forEach((v,k)=>{
            if(v[pidProp] == pid){
                let child = children(_this,v[idProp],deep+1);
                v.children = child;
                v.isLeaf = child.length ? 1 : 0;
                v.NODE_DEEP = deep+1;
                childList.push(Object.assign({},v));
            }
        });
        return childList;
    };
    return children(_this,startWith||0);
}